﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PvfUtilityDemo
{
    public partial class NewForm : Form
    {
        public static int port;
        public NewForm()
        {
            InitializeComponent();
            EventRegister();
            port = int.Parse(this.TextApiPort.Text);
        }
        private void EventRegister()
        {
            TextApiPortTextChanged();
            TestConnection();
            GetVersion();
            GetFileList();
            GetPvfRootDirectory();
            GetFileContent();
            GetFileContents();
            GetAllLstFileList();
            DeleteFile();
            DeleteFiles();
            ImportFile();
            ImportFiles();
            GetItemInfo();
            GetItemInfos();
            GetTreeListFocusedFilePath();
            GetSearchPanelTreeListFocusedFilePath();
            GetActiveDocumentFilePath();
            FileListToLstRows();
            FileIsExists();
            GetTreeSelectedFiles();
            GetSearchPanelSelectedFiles();
            SaveAsPvfFile();
            GetPvfPackFilePath();
            SearchPvf();
            ItemCodeToFileInfo();
            ItemCodesToFileInfos();
            GetFileIcon();
            GetLstFileInfo();
        }

        void TextApiPortTextChanged()
        {
            this.TextApiPort.TextChanged += (s, e) => {
                port = int.Parse(this.TextApiPort.Text);
            };
        }
        void TestConnection()
        {
            this.BtnTest.Click += (s, e) =>
            {
                if (this.TextApiPort.Text == "")
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {
                        string str = string.Empty;
                        var result = PvfUtilityConn.GetFileContent(port, "equipment/equipment.lst", false);
                        if (result != null)
                        {
                            str = result.Data;
                            this.TextResult.Text = str != null ? "Success" : "Failure";
                        }
                    }));
                });
            };
        }
        void GetVersion()
        {
            this.CheckGetVersion.CheckedChanged += (s, e) => {
                if (this.CheckGetVersion.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {
                        string str = string.Empty;
                        var result = PvfUtilityConn.GetVersion(port);
                        if (result != null)
                        {
                            str = result.Data;
                            this.TextResult.Text = str != null ? str : "Failure";
                        }
                    }));
                });
            };
        }
        void GetFileList()
        {
            this.CheckGetFileList.CheckedChanged += (s, e) => {
                if (this.CheckGetFileList.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {
                        string str = string.Empty;
                        var result = PvfUtilityConn.GetFileList(port, "equipment", ".equ");
                        if (result != null)
                        {
                            StringBuilder sb = new StringBuilder();
                            int i = 0;
                            foreach (var item in result.Data)
                            {
                                sb.AppendLine(item.ToString());
                                i++;
                            }
                            this.TextResult.Text = $"读取{i}个路径" + "\r\n" + sb.ToString();
                        }
                        else
                        {
                            this.TextResult.Text = string.Empty;
                        }

                    }));
                });
            };
        }
        void GetPvfRootDirectory()
        {
            this.CheckGetPvfRootDirectory.CheckedChanged += (s, e) =>
            {
                if (this.CheckGetPvfRootDirectory.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {
                        string str = string.Empty;
                        var result = PvfUtilityConn.GetPvfRootDirectory(port);
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < result.Data.Length; i++)
                        {
                            sb.AppendLine(result.Data[i]);
                        }
                        this.TextResult.Text = sb.ToString();
                    }));

                });
            };
        }
        void GetFileContent()
        {
            this.CheckGetFileContent.CheckedChanged += (s, e) => {
                if (this.CheckGetFileContent.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {
                        string str = string.Empty;
                        var result = PvfUtilityConn.GetFileContent(port, "equipment/character/swordman/weapon/ssword/lswd_gram.equ", false);
                        if (result != null)
                        {
                            str = result.Data;
                            this.TextResult.Text = str != null ? str : "Failure";
                        }

                    }));

                });
            
            };

        }
        void GetFileContents()
        {
            this.CheckGetFileContents.CheckedChanged += (s, e) => {
                if (this.CheckGetFileContents.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {
                        string str = string.Empty;
                        PostStr postStr = new PostStr()
                        {
                            FileList = new List<string>() { "creature/aquajello/aquajello.cre", "creature/aquajello/attackinfo/overskill.atk" },
                            UseCompatibleDecompiler = false
                        };
                        var result = PvfUtilityConn.GetFileContents(port, postStr);
                        StringBuilder sb = new StringBuilder();
                        if (result != null)
                        {
                            foreach (var m in result.Data)
                            {
                                foreach (var n in m.Value)
                                {
                                    sb.AppendLine(n.Key);
                                    sb.AppendLine(n.Value);
                                    sb.AppendLine("=======================================================");
                                }
                            }
                            str = sb.ToString();
                            this.TextResult.Text = str;
                        }
                    }));
                });
            };
        }
        void GetAllLstFileList()
        {
            this.CheckGetAllLstFileList.CheckedChanged += (s, e) => {
                if (this.CheckGetAllLstFileList.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {

                        string str = string.Empty;
                        var result = PvfUtilityConn.GetAllListFileList(port);
                        if (result != null)
                        {
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < result.Data.Length; i++)
                            {
                                sb.AppendLine(result.Data[i].ToString());
                            }
                            str = sb.ToString();
                            this.TextResult.Text = str;
                        }

                    }));

                });

            };
        }
        void DeleteFile()
        {
            this.CheckDeleteFile.CheckedChanged += (s, e) =>
            {
                if (this.CheckDeleteFile.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {
                        string filePath = "equipment/character/swordman/weapon/ssword/lswd_gram.equ";
                        bool result = PvfUtilityConn.DeleteFile(port, filePath);
                        if (result == true)
                        {
                            this.TextResult.Text = $"删除成功!删除路径为{filePath}";

                        }
                        else
                        {
                            this.TextResult.Text = $"删除失败!{filePath}未找到或已删除";
                        }

                    }));

                });
            };
        }
        void DeleteFiles()
        {
            this.CheckDeleteFiles.CheckedChanged += (s, e) =>
            {
                if (this.CheckDeleteFiles.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {
                        List<string> list = new List<string>()
                    {
                    "equipment/character/common/amulet/lgcy_bbrooch_epereal.equ",
                    "equipment/character/common/amulet/lgcy_bneck_fate.equ",
                    "equipment/character/common/amulet/lgcy_bneck_hugh.equ",
                    };
                    var result = PvfUtilityConn.DeleteFiles(port, list);
                    if (result.Data.Length == 0 || result.Data == null)
                    {
                        this.TextResult.Text = "批量删除成功";
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < result.Data.Length; i++)
                        {
                            sb.AppendLine(result.Data[i]);
                        }
                        this.TextResult.Text = "批量删除失败的文件列表：\r\n" + sb.ToString();
                    }

                    }));
                });
            };
        }
        void ImportFile()
        {
            this.CheckImportFile.CheckedChanged += (s, e) =>
            {
                if (this.CheckImportFile.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {

                    this.Invoke(new Action(() =>
                    {
                        string filePath = @"C:\Users\Administrator\Desktop\equipment\character\common\amulet\11582.equ";
                        string str = File.ReadAllText(filePath, Encoding.UTF8);
                        bool result = PvfUtilityConn.ImportFile(port, @"equipment/character/common/amulet/11582.equ", str);
                        if (result == true)
                            this.TextResult.Text = $"上传成功！上传路径为{filePath}";
                        else
                        {
                            this.TextResult.Text = "上传失败";
                        }

                    }));
                });
            };
        }
        void ImportFiles()
        {
            this.CheckImportFiles.CheckedChanged += (s, e) => {
                if (this.CheckImportFiles.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {
                        string[] filePath =
                        {
                        @"C:\Users\Administrator\Desktop\equipment\character\common\amulet\1111111.equ",
                        @"C:\Users\Administrator\Desktop\equipment\character\common\amulet\2222222.equ",
                        @"C:\Users\Administrator\Desktop\equipment\character\common\amulet\3333333.equ"
                    };

                        List<UploadStr> list = new List<UploadStr>()
                    {
                    new UploadStr{FilePath="equipment/character/common/amulet/1111111.equ",FileContent=File.ReadAllText(filePath[0])},
                    new UploadStr{FilePath="equipment/character/common/amulet/2222222.equ",FileContent=File.ReadAllText(filePath[1])},
                    new UploadStr{FilePath="equipment/character/common/amulet/3333333.equ",FileContent=File.ReadAllText(filePath[2])},
                    };

                        var result = PvfUtilityConn.ImportFiles(port, list);
                        if (result == true)
                        {
                            this.TextResult.Text = "批量上传成功";
                        }
                        else
                        {
                            this.TextResult.Text = "批量上传失败";
                        }
                    }));
                });
            };
        }
        void GetItemInfo()
        {
            this.CheckGetItemInfo.CheckedChanged += (s, e) =>
            {
                if(this.CheckGetItemInfo.Checked!=true)
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {
                        var result = PvfUtilityConn.GetItemInfo(port, "equipment/character/common/amulet/lgcy_neck_red.equ");
                        if (result == null)
                            return;
                        this.TextResult.Text = $"{result.Data.ItemName}---{result.Data.ItemCode}";

                    }));

                });
            };

        }
        void GetItemInfos()
        {
            this.CheckGetItemInfos.CheckedChanged += (s, e) => {
                if (this.CheckGetItemInfos.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {

                    this.Invoke(new Action(() =>
                    {
                        List<string> list = new List<string>()
                    {
                        "equipment/character/common/amulet/100300001.equ",
                        "equipment/character/common/amulet/100300004.equ",
                        "equipment/character/common/amulet/100300008.equ",
                    };
                        var result = PvfUtilityConn.GetItemInfos(port, list);
                        if (result == null)
                            return;
                        StringBuilder sb = new StringBuilder();
                        foreach (var m in result.Data)
                        {
                            sb.AppendLine($"Path: {m.Key}");
                            sb.AppendLine($"ItemName: {m.Value.ItemName} --- ItemCode: {m.Value.ItemCode}");
                        }
                        this.TextResult.Text = sb.ToString();
                    }));
                });
            };
        }
        void GetTreeListFocusedFilePath()
        {
            this.CheckGetTreeListFocusedFilePath.CheckedChanged += (s, e) =>
            {
                if (this.CheckGetTreeListFocusedFilePath.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {
                        var result = PvfUtilityConn.GetTreeListFocusedFilePath(port);
                        if (result == null)
                            return;
                        this.TextResult.Text = result.Data;
                    }));
                });
            };
        }
        void GetSearchPanelTreeListFocusedFilePath()
        {
            this.CheckGetSearchPanelTreeListFocusedFilePath.CheckedChanged += (s, e) =>
            {
                if (this.CheckGetSearchPanelTreeListFocusedFilePath.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {

                    this.Invoke(new Action(() =>
                    {
                        var result = PvfUtilityConn.GetSearchPanelTreeListFocusedFilePath(port);
                        if (result == null)
                            return;
                        this.TextResult.Text = result.Data;


                    }));

                });

            };

        }
        void GetActiveDocumentFilePath()
        {
            this.CheckGetActiveDocumentFilePath.CheckedChanged += (s, e) => {

                if (this.CheckGetActiveDocumentFilePath.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {
                        var result = PvfUtilityConn.GetActiveDocumentFilePath(port);
                        if (result == null)
                            return;
                        this.TextResult.Text = result.Data;
                    }));
                });
            };
        }
        void FileListToLstRows()
        {
            this.CheckFileListToLstRows.CheckedChanged += (s, e) =>
            {
                if (this.CheckFileListToLstRows.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() =>
                {
                    this.Invoke(new Action(() =>
                    {
                        List<string> list = new List<string>()
                {
                    "equipment/character/common/amulet/100300001.equ",
                    "equipment/character/common/amulet/100300004.equ",
                    "equipment/character/common/amulet/100300008.equ",
                };
                        var result = PvfUtilityConn.FileListToLstRows(port, list);
                        if (result == null)
                            return;
                        StringBuilder sb = new StringBuilder();
                        foreach (var m in result.Data)
                        {
                            sb.AppendLine(m.Key);
                            foreach (var n in m.Value)
                            {
                                sb.AppendLine($"`{n.Key}`\t{n.Value}");
                            }
                        }
                        this.TextResult.Text = sb.ToString();

                    }));

                });

            };
        }
        void FileIsExists()
        {
            this.CheckFileIsExists.CheckedChanged += (s, e) => {

                if (this.CheckFileIsExists.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {

                    this.Invoke(new Action(() =>
                    {
                        bool result = PvfUtilityConn.FileIsExists(port, "equipment/character/common/amulet/11525.equ");
                        if (result == true)
                            this.TextResult.Text = "true";
                        else
                            this.TextResult.Text = "false";
                    }));

                });
            
            };
        }
        void GetTreeSelectedFiles()
        {
            this.CheckGetTreeSelectedFiles.CheckedChanged += (s, e) =>
            {
                if (this.CheckGetTreeSelectedFiles.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {

                    this.Invoke(new Action(() =>
                    {
                        var result = PvfUtilityConn.GetTreeSelectedFiles(port);
                        if (result == null)
                            return;
                        StringBuilder sb = new StringBuilder();
                        foreach (var item in result.Data)
                        {
                            sb.AppendLine(item);
                        }
                        this.TextResult.Text = sb.ToString();
                    }));
                });
            };
        }
        void GetSearchPanelSelectedFiles()
        {
            this.CheckSearchPanelSelectedFiles.CheckedChanged += (s, e) => {
                if (this.CheckSearchPanelSelectedFiles.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {

                    this.Invoke(new Action(() =>
                    {
                        var result = PvfUtilityConn.GetSearchPanelSelectedFiles(port);
                        if (result == null)
                            return;
                        StringBuilder sb = new StringBuilder();
                        foreach (var item in result.Data)
                        {
                            sb.AppendLine(item);
                        }
                        this.TextResult.Text = sb.ToString();
                    }));

                });
            
            };
        }
        void SaveAsPvfFile()
        {
            this.CheckSaveAsPvfFile.CheckedChanged += (s, e) => {
                if (this.CheckSaveAsPvfFile.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() => {
                    this.Invoke(new Action(() =>
                    {
                        FolderBrowserDialog dlg = new FolderBrowserDialog()
                        {
                            Description = "选中保存的文件夹",
                        };

                        if (dlg.ShowDialog() == DialogResult.OK)
                        {
                            string savePath = dlg.SelectedPath + @"\.Script.Pvf";
                            var result = PvfUtilityConn.SaveAsPvfFile(port, savePath);
                            if (result.IsError == false)
                                this.TextResult.Text = "保存成功";
                            else
                                this.TextResult.Text = "保存失败";

                        }

                    }));

                });
            };
        }
        void GetPvfPackFilePath()
        {
            this.CheckPvfPackFilePath.CheckedChanged += (s, e) => {

                if (this.CheckPvfPackFilePath.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() =>
                {
                    this.Invoke(new Action(() =>
                    {
                        var result = PvfUtilityConn.GetPvfPackFilePath(port);
                        if (result == null)
                            return;
                        this.TextResult.Text = result.Data;
                    }));
                });
            };
        }
        void SearchPvf()
        {
            this.CheckSearchPvf.CheckedChanged += (s, e) => { 
            
                if(this.CheckSearchPvf.Checked!=true)
                    return;
                var task = Task.Factory.StartNew(() =>
                {
                    this.Invoke(new Action(() =>
                    {
                        SearchStr searchStr = new SearchStr()
                        {
                            //搜索目录
                            SearchFolder = "dungeon",
                            //搜索关键字
                            Keyword = "[ancient dungeon]",
                            //搜索类型 整数？字符串？名称？脚本内容？
                            Type = 1,
                            //搜索源类型 0=全部类型 1=在搜索结果中删除 2=在搜索结果中查找
                            SourceType = 0,
                            //搜索时是否模糊搜索 是否使用正则
                            NormalUsing = 1,
                            //开头匹配
                            IsStartMatch = true,
                            //要进行筛选的搜索结果集合 如果是从查找结果二次搜索 请在此处传入要搜索的文件路径集合
                            SearchResult = null,
                            //搜索路径
                            IsUseLikeSearchPath = false,
                            //特征搜索
                            Trait = false,
                            //使用正则表达式
                            UseRegularExpression = false,
                            //全词匹配
                            WholeWordMatch = false,
                            //文件类型排除还是保留
                            RemoveOrKeep = 1,
                            //要保留或排除的文件类型集合 .equ .ani 如无需使用保持NULL
                            FileTypesString = null,
                            //脚本文件搜索内容
                            ScriptContent = "",
                            //特征搜索 开始内容
                            ScriptContentStart = "",
                            //特征搜索 结束内容
                            ScriptContentStop = "",
                        };
                        var result = PvfUtilityConn.SearchPvf(port, searchStr);
                        if (result == null)
                            return;
                        StringBuilder sb = new StringBuilder();
                        foreach (var item in result.Data)
                        {
                            sb.AppendLine(item);
                        }
                        this.TextResult.Text = sb.ToString();

                    }));
                });
            };
        }
        void ItemCodeToFileInfo()
        {
            this.CheckItemCodeToFileInfo.CheckedChanged += (s, e) => {

                if (this.CheckItemCodeToFileInfo.Checked != true) 
                    return;
                var task = Task.Factory.StartNew(() =>
                {
                    this.Invoke(new Action(() =>
                    {
                        var result = PvfUtilityConn.ItemCodeToFileInfo(port, "equipment", 27098);
                        if (result == null)
                            return;
                        this.TextResult.Text = $"{result.Data.FilePath}\r\n{result.Data.ItemName}";

                    }));
                });
            };
        }
        void ItemCodesToFileInfos()
        {
            this.CheckItemCodesToFileInfos.CheckedChanged += (s, e) =>
            {
                if (this.CheckItemCodesToFileInfos.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() =>
                {
                    this.Invoke(new Action(() =>
                    {
                        PostInfo postInfo = new PostInfo()
                        {
                            lstNames = new List<string> { "equipment", "stackable" },
                            ItemCodes = new List<int> { 1251, 27098 },
                        };
                        var result = PvfUtilityConn.ItemCodesToFileInfos(port, postInfo);
                        if (result == null)
                            return;
                        StringBuilder sb = new StringBuilder();
                        foreach (var m in result.Data)
                        {
                            foreach (var n in m.Value)
                            {
                                sb.AppendLine(n.Key);
                                sb.AppendLine(n.Value.FilePath);
                                sb.AppendLine(n.Value.ItemName);
                            }
                        }
                        this.TextResult.Text = sb.ToString();

                    }));
                });
            };
        }
        void GetFileIcon()
        {
            this.CheckGetFileIcon.CheckedChanged += (s, e) =>
            {
                if (this.CheckGetFileIcon.Checked != true)
                {
                    this.TextResult.Visible = true;
                    return;
                }
                this.TextResult.Visible = false;
                var task = Task.Factory.StartNew(() => {

                    this.Invoke(new Action(() => {

                        PictureBox pictureBox = new PictureBox()
                        {
                            Location = new Point(29, 50),
                            Size = new Size(60, 60),
                            SizeMode = PictureBoxSizeMode.Zoom,
                        };
                        this.Group3.Controls.Add(pictureBox);

                        var result = PvfUtilityConn.GetFileIcon(port, "equipment/character/swordman/weapon/ssword/n_sswd_eleno.equ");
                        if (result == null)
                            return;
                        pictureBox.Image = Base64Convert.Base64ToImage(result.Data);


                    }));
                });


            };
        }
        void GetLstFileInfo()
        {
            this.CheckGetLstFileInfo.CheckedChanged += (s, e) =>
            {
                if (this.CheckGetLstFileInfo.Checked != true)
                    return;
                var task = Task.Factory.StartNew(() =>
                {
                    this.Invoke(new Action(() => 
                    { 
                       var result = PvfUtilityConn.GetLstFileInfo(port);
                       if (result == null)
                           return;
                       StringBuilder sb = new StringBuilder();
                       foreach (var item in result.Data.Values)
                       {
                           sb.AppendLine($"{item.ItemName},{item.ItemCode},{item.PathHeader},{item.ItemPath},{item.FullPath}");
                       }
                       this.TextResult.Text = sb.ToString();
                    }));

                });
            
            };

            


        }

    }
}
